package com.yi.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 数据库配置文件读取
 * @author YI
 * @date 2018-3-18 19:38:39
 */
@Component
@EnableCaching
@Configuration
@PropertySource("classpath:config/db-example-hikari.properties")
public class HikariDataSourceProperties {

    @Value("${hikari.url}")
    private String url;
    @Value("${hikari.username}")
    private String username;
    @Value("${hikari.password}")
    private String password;
    @Value("${hikari.driver}")
    private String driver;
    @Value("${hikari.autoCommit}")
    private Boolean autoCommit;
    @Value("${hikari.connectionTimeout}")
    private Long connectionTimeout;
    @Value("${hikari.idleTimeout}")
    private Long idleTimeout;
    @Value("${hikari.maxLifetime}")
    private Long maxLifetime;
    @Value("${hikari.connectionTestQuery}")
    private String connectionTestQuery;
    @Value("${hikari.minimumIdle}")
    private Integer minimumIdle;
    @Value("${hikari.maximumPoolSize}")
    private Integer maximumPoolSize;
    @Value("${hikari.readOnly}")
    private Boolean readOnly;

    /**
     * 必须配置dataSource，否则无法连接数据库
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource dataSourceConfig(){
        HikariDataSource hikariDataSource = new HikariDataSource();

        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);
        hikariDataSource.setDriverClassName(driver);

        hikariDataSource.setAutoCommit(autoCommit);
        hikariDataSource.setConnectionTimeout(connectionTimeout);
        hikariDataSource.setIdleTimeout(idleTimeout);
        hikariDataSource.setMaxLifetime(maxLifetime);
        hikariDataSource.setMinimumIdle(minimumIdle);
        hikariDataSource.setMaximumPoolSize(maximumPoolSize);
        hikariDataSource.setReadOnly(readOnly);

        return hikariDataSource;
    }
}
